package service;

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

import util.Java_JDBC;

import config.Config;
import config.SocketConfig;

public class SunVoteServer implements Runnable{
	Java_JDBC java_JDBC = null;
	ServerSocket serverSocket = null;

	public SunVoteServer() {
		try {
			serverSocket = new ServerSocket();
			serverSocket.bind(new InetSocketAddress(SocketConfig.ipAddress, SocketConfig.socketPort));
			InetAddress inet = serverSocket.getInetAddress();
			System.out.println("inet: "+inet);
			System.out.println("服务器等待连接" + inet.getHostAddress() + "   端口号："
					+ SocketConfig.socketPort);
			java_JDBC = dateServer();
		}catch (Exception e) {
			e.printStackTrace();
			try {
				serverSocket.close();
				java_JDBC = null;
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
	}
	
	@Override
	public void run() {
		while (true) {
			Socket socket;
			try {
				socket = serverSocket.accept();
				Thread thread = new Thread(new ServerThread(socket, java_JDBC));
				thread.start();
			} catch (Exception e) {
			}
		}
	}

	// 操作数据库时间限制，长时间会抛出异常
	public ExecutorService executor = Executors.newSingleThreadExecutor();

	public Java_JDBC dateServer() throws Exception {
		Future<Java_JDBC> future = executor.submit(new Callable<Java_JDBC>() {
			@Override
			public Java_JDBC call() throws Exception {
				return new Java_JDBC();
			}
		});
		System.out.println("执行完毕了Java_JDBC");
		return future.get(2000, TimeUnit.MILLISECONDS);
	}
}
